package com.zzy.controller;

import com.zzy.dao.PathDao;
import com.zzy.entity.FilePath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.UUID;

@Controller
public class UploadFile {

    @Autowired
    private PathDao pathDao;

    @GetMapping("/")
    public String index(){
        return "index";
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("title") String title, Model model, HttpServletRequest request) throws IOException {

        String uploadPath ="/opt/zzy/resource/";

        File file1 = new File(uploadPath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        //获取文件名
        String originalFilename = file.getOriginalFilename();

        //获取后缀名
        String[] split = originalFilename.split("\\.");
        String pre = split[split.length-1];

        //创建新的文件名
        UUID uuid = UUID.randomUUID();
        String s = uuid.toString()+"."+pre;

        //存入
        file.transferTo(new File(file1.getAbsolutePath(),s));


        //获取端口
        int port = request.getServerPort();
        //获取主机地址
        String HOST = "1.117.235.236";
        // 请求的地址
        String pathFile = HOST+":"+port+"/static/"+s;

        //保存数据地址
        FilePath filePath = new FilePath();
        filePath.setUrlPath(pathFile);
        System.out.println(title);
        filePath.setTitle(title);
        pathDao.save(filePath);

        model.addAttribute("msg","上传成功");
        return "index";
    }

    @GetMapping("/download")
    public String downLoad(Model model){
        List<FilePath> filePaths = pathDao.allPath();
        model.addAttribute("filepaths",filePaths);
        return "load";
    }

}
